package com.xxljob.demo.core.util;

import com.xxljob.demo.core.conf.XxlJobAdminConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import java.io.IOException;
import java.text.MessageFormat;
import java.util.Objects;
import java.util.Properties;

public class I18nUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(I18nUtil.class);

    private static Properties prop = null;

    public static Properties loadI18nProp() {
        if (Objects.nonNull(prop)) {
            return prop;
        }
        try {
            // build i18n prop
            String i18n = XxlJobAdminConfig.getAdminConfig().getI18n();
            String i18nFile = MessageFormat.format("i18n/message_{0}.properties", i18n);

            Resource resource = new ClassPathResource(i18nFile);
            EncodedResource encodedResource = new EncodedResource(resource, "UTF-8");

            prop = PropertiesLoaderUtils.loadProperties(encodedResource);
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }
        return prop;
    }

    public static String getString(String key) {
        return loadI18nProp().getProperty(key);
    }

}
